package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQueryObject;
import cn.wolfcode.wolf2w.repository.RegionRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.util.DBHelp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
//@Transactional
public class RegionServiceImpl implements IRegionService {


    @Autowired
    private RegionRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Region region) {
        region.setId(null);
        repository.save(region);

    }

    @Override
    public void update(Region region) {
        repository.save(region);

    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);

    }

    @Override
    public Region get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return repository.findAll();
    }

    @Override
    public Page<Region> query(RegionQueryObject qo) {

        //MQL语句拼接
        Query query = new Query();

        //分页查询语句
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC,"_id");
        Page<Region> page = DBHelp.query(template, Region.class, pageable, query);

        return page;
    }

    @Override
    public void saveOrUpdate(Region region) {
        if (StringUtils.hasLength(region.getId())){
            //更新
            this.update(region);
        }else {
            //添加
            this.save(region);

        }
    }

    @Override
    public void changeHotValue(int hot, String id) {
        //部分字段更新
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("ishot", hot);
        template.updateMulti(query, update, Region.class);

    }

    @Override
    public List<Region> queryHotRegions() {
        return repository.findByIshotOrderBySequence(Region.STATE_HOT);
    }


}
